//
//  IcDeIcingTipsViewController.m
//  IceClear
//
//  Created by P & C on 4/6/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "IcDeIcingTipsViewController.h"
#import "IcMaterial.h"


@implementation IcDeIcingTipsViewController

@synthesize appModelsManager;


/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
 if (self) {
 // Custom initialization.
 //.....
 }
 return self;
 }
 */

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
	NSMutableString* strBuilder = [NSMutableString string];
	NSMutableArray* vals = [NSMutableArray array];
	
	for (NSNumber * n in [[self.appModelsManager.recommendationsManager.drySaltingRates allValues] reverseObjectEnumerator]) {
		[vals addObject:[NSString stringWithFormat:@"%d", [n intValue]]];
	}
	
	[strBuilder appendString:@"http://chart.apis.google.com/chart?chxl=2:|lbs%2Fm2|3:|Pavement+Temp+(C)&chxp=2,15|3,-18&chxr=0,0,30|1,-35,0|2,0,30|3,-35,0&chxt=y,x,y,x&chs=280x200&cht=lxy&chco=3072F3&chds=0,30,0,30&chdl=Salt+Amount&chdlp=b&chg=0,17,0,0&chls=2&chma=5,5,5,25|0,14&chtt=Salting+Rates&chts=660000,12"];
	
	[strBuilder appendFormat:@"&chd=t:-1|%@", [vals componentsJoinedByString:@","]];
	
	// finalize the google charts api url
	NSString* googleChartsUrl = [NSString stringWithFormat:@"%@", strBuilder];
	
	NSLog(@"Google charts url: %@", googleChartsUrl);
	
	// put it in a html string
	NSString* htmlFormat = @"<html><head><title>None</title></head><body><center><img src=\"%@\" /></center></body>";
	NSString* html = [NSString stringWithFormat:htmlFormat, googleChartsUrl];
	
	// grab materials that are good for ant-icing from our material models manager
	IcMaterial* m1 = [self.appModelsManager.materialsManager materialNamed:@"nacl"];
	IcMaterial* m2 = [self.appModelsManager.materialsManager materialNamed:@"cacl"];
	IcMaterial* m3 = [self.appModelsManager.materialsManager materialNamed:@"mgcl"];
	
	// set up the data of the table view with each section and its rows
	// first element will be the title of the section while the second
	// will hold the date used to build the cells of the different rows
	NSArray* introSection = [NSArray arrayWithObjects:@"", [NSArray arrayWithObject:@"   De-icing chemical agents remove existing snow ice, frost, etc. It does not melt all the snow; it seeps through to the surface of the pavement and melts the ice there, breaking the bond and making it easier to remove the snow."], nil]; 
	NSArray* materialsSection = [NSArray arrayWithObjects:@"Materials", [NSArray arrayWithObject:@"Road Salts are the most commonly used materials for de-icing.\nRock salt is the most effective for temperatures above -10 C. Below that Calcium Chloride, which is economically feasible and environmentally friendly, is used up to -31 C. \nOther road salts include urea, magnesium chloride, potassium acetate, potassium chloride and calcium magnesium acetate."], nil];
	NSArray* productsSection = [NSArray arrayWithObjects:@"Recommended Products", 
								[NSArray arrayWithObjects:[m1.suggestedProducts objectAtIndex:0], 
								 [m2.suggestedProducts objectAtIndex:0], [m3.suggestedProducts objectAtIndex:0],
								 nil], 
								nil];
	NSArray* ratesSection = [NSArray arrayWithObjects:@"Application Rates", [NSArray arrayWithObject:html], nil];
	
	tblTipsData = [[NSMutableArray array] retain];
	
	// add different sections together into one wrapping array
	[tblTipsData addObject:introSection];
	[tblTipsData addObject:materialsSection];
	[tblTipsData addObject:productsSection];
	[tblTipsData addObject:ratesSection];
	
	self.view.backgroundColor = [UIColor clearColor];
	lblHeading.backgroundColor = [UIColor clearColor];
	tblTips.backgroundColor = [UIColor clearColor];
}

/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations.
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


#pragma mark -
#pragma mark UITableView delegation

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	//if (tableView.tag == 0) {
	return [self numberOfSectionsInTableViewForTblTips: tableView];
	//}
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	//if (tableView.tag == 0) {
	return [self numberOfRowsInSectionForTblTips: section];
	//}
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
	return [self cellForRowAtIndexPathForTblTips: indexPath];
	//}
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	//if (tableView.tag == 0) {
	return [self titleForHeaderInSectionForTblTips: section];
	//}
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
	return [self heightForRowAtIndexPathForTblTips: indexPath];
	//}
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
	return [self didSelectRowAtIndexPathForTblTips: indexPath];
	//}
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	//if (tableView.tag == 0) {
	return [self willSelectRowAtIndexPathForTblTips: indexPath];
	//}
}


- (NSInteger)numberOfSectionsInTableViewForTblTips:(UITableView *)tableView {
	return [tblTipsData count];
}

- (NSInteger)numberOfRowsInSectionForTblTips:(NSInteger)section {
	return [[[tblTipsData objectAtIndex:section] objectAtIndex:1] count];
}

- (CGFloat)heightForRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	float val = 200;
	
	switch (indexPath.section) {
		case 0:
			val = 100;
			break;
			
		case 2:
			val = 30;
			break;
		case 3:
			val = 250;
			break;
			
		default:
			break;
	}
	
	return val;
}

- (void)didSelectRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	if (indexPath.section == 2) {
		// when a recommended product is clicked launch the browser
		// to that product's web site
		[[UIApplication sharedApplication] openURL:[[[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] 
													 objectAtIndex:indexPath.row] objectAtIndex:1]];
	}
}

- (UITableViewCell *)cellForRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	static NSString* tblCellIdentifier = @"identifier.tbl.reuseablecell";
	static NSString* tblCellIdentifier2 = @"identifier.tbl.reuseablecell.withwebview2";
    UITableViewCell* cell = [tblTips dequeueReusableCellWithIdentifier:tblCellIdentifier];
	
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tblCellIdentifier] autorelease];
    }
	
	// customize the cell
	
	if (indexPath.section == 2) {
		// the third section is about the recommended products
		// the format of the data source for this section is:
		// - Root (Array)
		//		- Products Section (Array)
		//			- Title (String)
		//			- Products (Array)
		//				- Product (Array)
		//					- Name (String)
		//					- Url (URL)
		cell.textLabel.text = [[[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] objectAtIndex:indexPath.row] 
							   objectAtIndex: 0];
	}
	else if (indexPath.section == 3) {
		cell = [tblTips dequeueReusableCellWithIdentifier:tblCellIdentifier2];
		
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tblCellIdentifier2] autorelease];
			
			UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectMake(5, 5, 285, 230)];
			
			cell.textLabel.text = nil;
			
			// remove previously added subviews
			for (UIView *v in cell.contentView.subviews) {
				[v removeFromSuperview];
			}
			// add the web view to the content view
			[cell.contentView addSubview:webView];
			// load the html string
			[webView loadHTMLString:[[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] objectAtIndex:indexPath.row] 
							baseURL:[NSURL URLWithString:@"http://www.google.com"]];
			
			[webView release];
		}
	}
    else {
		// the format of the data source for other sections is:
		// - Root (Array)
		//		- Any Other Section (Array)
		//			- Title (String)
		//			- Contents (Array)
		//				- Content (String)
		cell.textLabel.text = [[[tblTipsData objectAtIndex:indexPath.section] objectAtIndex:1] objectAtIndex:indexPath.row];
		cell.textLabel.numberOfLines = 0;
		cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
		cell.textLabel.font = [UIFont systemFontOfSize:13];
	}
	
    return cell;
}

- (NSString *)titleForHeaderInSectionForTblTips:(NSInteger)section {
	return [[tblTipsData objectAtIndex:section] objectAtIndex: 0];
}

- (NSIndexPath *)willSelectRowAtIndexPathForTblTips:(NSIndexPath *)indexPath {
	// only clicks on third section (recommended products)
	if (indexPath.section == 2) {
		return indexPath;
	}
	else {
		return nil;
	}
	
}


#pragma mark -
#pragma mark memory management

- (void)dealloc {
	[tblTips release];
	[tblTipsData release];
	[appModelsManager release];
	[lblHeading release];
    [super dealloc];
}


@end
